package com.sky.service.impl;

import com.github.pagehelper.PageException;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.Employee;
import com.sky.exception.*;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //MD5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        log.info("密码MD5加密:{}", password);
        //密码比对
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //3、返回实体对象
        return employee;
    }

    /**
     * 添加员工
     * @param    employeeDTO
     * @return   返回受影响行数
     */
    @Override
    public Integer addEmp(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //属性拷贝(浅拷贝)
        BeanUtils.copyProperties(employeeDTO, employee);
        //处理未填充字段
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        employee.setStatus(StatusConstant.DISABLE);
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        //创建者与更新者使用id 使用ThreadLocal变量存储
        Long managerId = BaseContext.getCurrentId();
        log.info("创建(更新)者id:{}", managerId);
//        employee.setCreateUser(managerId);
//        employee.setUpdateUser(managerId);
        //存入数据库中
        log.info("添加用户进入数据库:{}", employee);
        int ret = employeeMapper.add(employee);
        log.info("返回结果:{}",ret);
        if (ret == 0) {
            throw new AccountAddException("用户添加失败,可能已存在该用户");
        }
        return ret;
    }

    /**
     * 员工分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageEmp(EmployeePageQueryDTO employeePageQueryDTO) {
        //查询总个数
        Integer total = employeeMapper.total();
        log.info("员工个数:{}",total);
        //获取当前页面
        Integer page = employeePageQueryDTO.getPage();
        //是否有指定查询用户
        String name = employeePageQueryDTO.getName();
        //限定页面大小
        Integer pageSize = employeePageQueryDTO.getPageSize();
        //计算起始页面
        Integer start = (page - 1) * pageSize;
        log.info("从第{}开始查询,每页{}个", start, pageSize);
        List le = employeeMapper.pageEmp(name, start, pageSize);
        log.info("查询员工:{}",le);
        if(le == null || le.isEmpty()){
            throw new BaseException("分页查询失败");
        }
        //包装返回值
        PageResult pageResult = new PageResult();
        pageResult.setTotal(total);
        pageResult.setRecords(le);
        return pageResult;
    }

    /**
     * 设置员工状态
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public Integer setStatus(Integer id, Integer status) {
        //填充字段
        EmployeeSetStatus employeeSetStatus = EmployeeSetStatus.builder()
                                                .id(id)
                                                .status(status)
                                                .updateTime(LocalDateTime.now())
                                                .updateUser(BaseContext.getCurrentId()).build();
        Integer ret = employeeMapper.setStatus(employeeSetStatus);
        log.info("管理员{}设置结果:{}",BaseContext.getCurrentId(), ret);
        if(ret == 0) {
            throw new BaseException();
        }
        return ret;
    }

    /**
     * 修改员工密码
     * @param passwordEditDTO
     */
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        //从线程上下文获取用户id
        passwordEditDTO.setEmpId(BaseContext.getCurrentId());
        //对新密码加密
        passwordEditDTO.setNewPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));
        //补充更新字段
//        passwordEditDTO.setUpdateUser(BaseContext.getCurrentId());
//        passwordEditDTO.setUpdateTime(LocalDateTime.now());
        //开始修改
        Integer ret = employeeMapper.editPassWord(passwordEditDTO);
        log.info("修改结果:{}",ret);
        if(ret == 0){
            throw new BaseException();
        }
    }

    @Override
    public Employee getEmpById(Integer id) {
        log.info("查询id:{}", id);
        Employee employee =  employeeMapper.getempById(id);
        if(employee == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        log.info("查找员工结果:{}",employee);
        return employee;
    }

    @Override
    public void updateEmp(EmployeeDTO employeeDTO) {
        //填充默认字段
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        //更新员工信息
        Integer ret = employeeMapper.updateEmp(employee);
        if (ret == 0) {
            throw new BaseException("员工信息更新失败");
        }
        log.info("员工更新成功");
    }
}
